$(function () {
    loadTeacherList();
});

function loadTeacherList() {
    $.ajax(
        {
            url: "/api/teacher/list"
        }
    ).done(function (data) {
        let html = "";
        data.forEach((element, index) => {
            html += '<tr>'
            html += '<td>' + element.id + '</td>'
            html += '<td>' + element.name + '</td>'
            html += '<td>' + element.sex + '</td>'
            html += '<td>' + element.tno + '</td>'
            html += '<td>' + element.age + '</td>'

            html += "<td> <a href='#' onclick='showTeacherDlg(" + element.id
                + ")'>编辑</a> &nbsp; &nbsp;<a href='#' onclick='deleteById(" +element.id
                + ")'>删除</a> </td>"
            html += '</tr>'
        })
        $("#teacherTb").html(html)
    })
}


let layerIndex;

/*
* 弹出新增/更新对话框
* */
function showTeacherDlg(id) {
    let title = "新增教师"
    // 重置提交按钮状态（启用按钮）
    $("#btnOK").prop("disabled", false).removeClass("layui-btn-disabled");
    if (id) {
        title = "编辑教师";
        $("#formId").css("display", "block");
        $.ajax({
            //通过id读取信息
            url: "/api/teacher/" + id,
            method: "GET"
        }).done(result => {
            console.log(result)
            $.each(result, function (key, value) {
                var filed = $('#teacForm [name = "' + key + '"]');
                if (filed.is(":radio")) {
                    filed.filter('[value = "' + value + '"] ').prop("checked", true);
                } else if (filed.is(":checkbox")) {
                    filed.prop("checked", value === 'yes');
                } else {
                    filed.val(value);
                }
            })
        })
    } else {
        $("#teacForm")[0].reset();
        $("#formId").css("display", "none");
    }

    layerIndex = layer.open(
        {
            type: 1,
            title: title,
            area: ['450px', 'auto'],
            content: $('#teacForm')

        }
    )

}

layui.use(function () {
    layui.form.on('submit(teac-dlg)', function (data) {
        event.preventDefault(); //阻止表单默认提交

        commitTeaDlg();
    })
});

//自定义一个提交表单的函数
function commitTeaDlg() {
    let id = $("#id").val();
    let formData = $("#teacForm").serialize();
    if (id != null && id != "") {
        $.ajax({
            url: "/api/teacher/update",
            method: "PUT",
            data: formData
        }).done(result => {
            console.log(result);
            if (result.id) {
                loadTeacherList();

                console.log("update success!")
                if (layerIndex)
                    layer.close(layerIndex)
            }
        }).fail((jqXHR, textStatus, errorThrown) => {
            console.error("Request failed:" + textStatus + "-" + errorThrown);
            alert("An error occurred. Please try again.");
        });
    } else {
        $.ajax({
            url: "/api/teacher/add",
            method: "POST",
            data: formData
        }).done(result => {
            console.log(result);
            if (result.id) {
                loadTeacherList();

                console.log("add success!")
                if (layerIndex)
                    layer.close(layerIndex)
            }
        }).fail((jqXHR, textStatus, errorThrown) => {
            console.error("Request failed:" + textStatus + "-" + errorThrown);
            alert("An error occurred. Please try again.");
        });
    }

    $("#btnOK").prop("disabled", true).addClass("layui-btn-disabled");//禁用按钮

}

/**
 * 删除教师信息
 */
function deleteById(id) {
    layer.confirm('你确定要删除吗？一旦删除不可恢复！', {icon: 3}, function () {
        $.ajax({
            url: "/api/teacher/delete/" + id,
            method: "DELETE"
        }).done(result => {
            loadTeacherList();
        })
        layer.closeAll();  //关闭弹窗层

    }, function () {

    });
}